package com.web.template.sax;

import java.io.IOException;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.ext.DefaultHandler2;
import org.xml.sax.helpers.AttributesImpl;

public class Digester extends DefaultHandler2 {


  private StringBuffer bodyText = new StringBuffer();


  @Override
  public void startDocument() throws SAXException {
    super.startDocument();
  }

  @Override
  public void characters(char[] ch, int start, int length) throws SAXException {
    bodyText.append(ch, start, length);
  }

  /**
   * 遇到开始标签执行
   *
   * @param uri        命名空间URI 例如<a:b></a:b>
   * @param localName
   * @param qName
   * @param attributes
   * @throws SAXException
   */
  @Override
  public void startElement(String uri, String localName, String qName, Attributes attributes)
      throws SAXException {
    System.out.println(uri);
    System.out.println(localName);
    System.out.println("标签开始名称：" + qName);
    AttributesImpl newAttrs = new AttributesImpl(attributes);
    int nAttributes = newAttrs.getLength();
    StringBuffer attrStr = new StringBuffer();
    for (int i = 0; i < nAttributes; ++i) {
      String value = newAttrs.getValue(i);
      String name = newAttrs.getQName(i);
      attrStr.append("属性名：").append(name).append("   属性值：").append(value);
    }
    System.out.println(attrStr.toString());
  }

  @Override
  public void endDocument() throws SAXException {

  }

  @Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    System.out.println(uri);
    System.out.println(localName);
    System.out.println("标签结束名称：" + qName);
  }


  public InputSource resolveEntity(String name, String publicId,
      String baseURI, String systemId)
      throws SAXException, IOException {
    return null;
  }
}
